package com.alogic.xscript.plugins;


import com.alogic.load.Loader;
import org.apache.commons.lang3.StringUtils;

import com.alogic.validator.Validator;
import com.alogic.validator.ValidatorFactory;
import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.BaseException;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;

/**
 * 检查某个参数是否存在
 * 
 * @author duanyy
 * @version 1.6.8.14 [20170509 duanyy] <br>
 * - 增加xscript的中间文档模型,以便支持多种报文协议 <br>
 * 
 * @version 1.6.12.11 [20181206 duanyy] <br>
 * - 增加validator功能 <br>
 * 
 * @version 1.6.12.13 [20181213 duanyy] <br>
 * - 修正错误代码 <br>
 *
 * @version 1.6.13.17 [20200923 duanyy] <br>
 * - 优化validator接口 <br>
 *
 * @version 1.6.13.25 [20201110 duanyy] <br>
 * - 修复validator的问题
 *
 * @version 1.6.14.9 [20210507 duanyy] <br>
 * - validator的错误信息由validator本身输出 <br>
 */
public class Check extends AbstractLogiclet{
	protected String arguId;	
	protected String $code = "clnt.e2000";
	protected String $reason = "";
	protected String validatorId = null;
	protected static ValidateListener validateListener = new ValidateListener();
	
	public Check(String tag, Logiclet p) {
		super(tag, p);
	}

	@Override
	public void configure(Properties p) {
		super.configure(p);
		
		arguId = PropertiesConstants.getString(p,"id", arguId,true);
		$code = PropertiesConstants.getRaw(p,"code", $code);
		$reason = PropertiesConstants.getRaw(p,"reason", $reason);
		
		validatorId = PropertiesConstants.getString(p,"validator",validatorId,true);
	}		
	
	@Override
	protected void onExecute(XsObject root,XsObject current, LogicletContext ctx,
			ExecuteWatcher watcher) {
		if (StringUtils.isNotEmpty(arguId)){
			String value = ctx.GetValue(arguId, "");
			if (StringUtils.isEmpty(value)){
				throw new BaseException(
						PropertiesConstants.transform(ctx, $code, "clnt.e2000"),
						PropertiesConstants.transform(ctx, $reason, "Can not find parameter:" + arguId)
				);
			}
			
			if (StringUtils.isNotEmpty(validatorId)){
				Loader<Validator> loader = ValidatorFactory.getDefault();
				if (loader != null) {
					Validator validator = loader.load(validatorId, true);
					if (validator != null) {
						validator.check(value, ctx,validateListener);
					}
				}
			}
		}
	}

	public static class ValidateListener implements Validator.Listener{
		@Override
		public boolean result(boolean pass, String value, Validator validator, Properties ctx) {
			if (!pass) {
				throw new BaseException(validator.getCode(ctx),validator.getMessage(ctx));
			}
			return true;
		}
	}
}
